#include <sys/sem.h>  
#include <fcntl.h>  
#include <unistd.h>  
#include <errno.h>  
#include <sys/types.h>  
#include <sys/ipc.h>  
#include <sys/shm.h>  
#include <stdio.h>  

union semun{  
	int val;  
	struct semid_ds *buf;  
	unsigned short int *array;  
};  

main(int argc,char **argv)  
{  
	int i,shm_id,sem_id;  
	int value;  
	char *ptr;  
	struct sembuf lock_it;  
	union semun options;  

	if(argc!=2)  
	{  
		printf("usage:server <pathname>\n");  
		exit(1);  
	}  

	if((sem_id=semget(ftok(argv[1],0),0,0))<0)
		perror("semget");  

	if((shm_id=shmget(ftok(argv[1],0),4096,0))<0)  
		perror("shmget");  
	printf("key_t:%d\n",ftok(argv[1],0));  
	printf("shm_id:%d\n",shm_id);  
	
	if((ptr=shmat(shm_id,NULL,0))<0)  
		perror("shmat");  

	while(1)  
	{  
		lock_it.sem_num=0;  
		lock_it.sem_op=-1;  
		lock_it.sem_flg=IPC_NOWAIT;  
	
		semop(sem_id,&lock_it,1); 
		fgets(ptr,10,stdin);  
		printf("user:%s",ptr);  
		
		if((strcmp(ptr,"q\n"))==0)  
			exit(0);  
		lock_it.sem_num=0;  
		lock_it.sem_op=1;  
		lock_it.sem_flg=IPC_NOWAIT;  
		
		semop(sem_id,&lock_it,1); 
	}  

	shmdt(ptr);  
	exit(0);  
}  
